package com.maxlen.admin.security;

import com.maxlen.admin.entity.Admin;
import com.maxlen.admin.entity.bo.LoginDetailsBo;
import com.maxlen.admin.service.IAdminService;
import com.maxlen.admin.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * 通过用户名判断用户是否存在，封装然后返回
 */
@Component
public class CustomUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private IAdminService adminService;

    @Autowired
    private IRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Admin admin = adminService.findAdminByUsername(username);
        if(ObjectUtils.isEmpty(admin)){
            throw new UsernameNotFoundException("用户名不存在");
        }

        List<String> roleNameList = roleService.findRoleNameByAdminId(admin.getId());
        // LogUtils.log(CustomUserDetailServiceImpl.class, admin.toString());
        return new LoginDetailsBo(admin, roleNameList);
    }

}
